class Solution(object):
    def calcEquation(self, equations, values, queries):
        """
        :type equations: List[List[str]]
        :type values: List[float]
        :type queries: List[List[str]]
        :rtype: List[float]
        """
        nodes = {}
        for i in range(len(equations)):
            src,dst = equations[i]
            value = values[i]
            if src not in nodes:
                nodes.update({src:[]})
            nodes[src].append((dst,value))
            if dst not in nodes:
                nodes.update({dst:[]})
            nodes[dst].append((src,1.0/value))
        
        class FoundExp(Exception):
            def __init__(self, value):
                Exception.__init__(self)
                self.value = value

        dst = None
        already = None
        def find(src, acc):
            if src in already: return
            already.add(src)
            if src==dst: raise FoundExp(acc)
            if src in nodes:
                for ne, val in nodes[src]:
                    find(ne, acc*val)
            already.remove(src)
        
        ret = []
        for nome, denome in queries:
            dst = denome
            already = set()
            try:
                if nome in nodes:
                    find(nome, 1.0)
                    ret.append(-1.0)
                else:
                    ret.append(-1.0)
            except FoundExp as e:
                ret.append(e.value)
        return ret

print(Solution().calcEquation([["a","b"],["b","c"],["bc","cd"]],
[1.5,2.5,5.0],
[["a","c"],["c","b"],["bc","cd"],["cd","bc"]]))